#!/usr/bin/env python
# coding: utf-8
# %%
import os

# %%
import argparse
import fnmatch

# %%
def arg_parse():
    parser = argparse.ArgumentParser(description='''generate readme to show picture''')
    parser.add_argument('-i', '--indir', required=True, help='''input fold''') 
    parser.add_argument('-o', '--output', required=False, default='README.md', help='''Output folder''')
    parser.add_argument('-t', '--type', nargs="*", required=False, default=[".jpg", ".png"], help='''type''')
    args = parser.parse_args()
    return args

# %%
def search_pic(fold, filter_cond=[".jpg", ".png"]):
    searched_pic = []
    for f in os.listdir(fold):
        filename, suffix = os.path.splitext(f)
        if suffix in filter_cond:
            searched_pic.append(fold + os.sep + f)
    return searched_pic

# %%
def single_pic_html(file):
    templete_html = """> ## **{}**\n![{}]({})\n<hr>\n\n"""
    f_name, f_suffix = os.path.splitext(os.path.basename(file))
    single_html = templete_html.format(f_name, f_name, file.replace(" ", "%20"))
    return single_html

# %%
def generate_readme(fold, types):
    readme_html = ""
    for f in search_pic(fold, types):
        readme_html += single_pic_html(f)
    return readme_html

# %%
if __name__ == "__main__":
    args = arg_parse()
    fold_path = args.indir
    output = args.output
    type_list = args.type
    readme_html = generate_readme(fold_path, type_list)
    dir_path = os.path.dirname(output)
    if not os.path.exists(dir_path) and dir_path:
        os.makedirs(dir_path)
    with open(output, 'w') as f:
        f.write(readme_html)

# %%